package network.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//回显服务器
public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        this.socket = new DatagramSocket(port);//创建对象时手动指定端口号
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //对于服务器来说,需要不断地接受请求,返回响应
            //1.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4069],4069);
            socket.receive(requestPacket);//3.进入阻塞
            //从网卡读到udp数据报,就放到了requestPacket对象中了
            //其中Udp数据报载荷部分就被放到requestPacket内置的 字节数组 中了
            //另外报头部分,也会被requestPacket的其他属性保存
            //读到的字节数组,转换为String方便后续的逻辑处理
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());//基于字节数组构造String
            //2.根据请求计算响应(此处无需计算)
            String response = process(request);
            //3.把响应返回到客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length
                    ,requestPacket.getSocketAddress());
            socket.send(responsePacket);//7.服务器响应
            //打印日志
            System.out.printf("[%s:%d] req: %s,resp: %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }

    public String process(String request) {
        return request;//由于此处是回显服务器,所以此处直接return
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();//1.客户端启动
    }


}
